//
//  SubjectTableViewCell.m
//  LimitFree
//
//  Created by lijinghua on 16/3/2.
//  Copyright © 2016年 lijinghua. All rights reserved.
//

#import "SubjectTableViewCell.h"
#import "SubjectAppView.h"

@implementation SubjectTableViewCell

//当cell创建完成后调用awakeFromNib
//在这里可以对我们的视图做进一步的定制
- (void)awakeFromNib {
   //创建4个application对应的view，然后根据model中app的个数，来显示或隐藏appView
    [self createAppViews];
    //self.backgroundColor = [UIColor clearColor];
}


- (void)createAppViews{
    for (int index = 0; index < 4; index++) {
        //使用xib创建AppView
        UINib *nib = [UINib nibWithNibName:@"SubjectAppView" bundle:nil];
        SubjectAppView *appView = (SubjectAppView*)[[nib instantiateWithOwner:nil options:nil] firstObject];
        //设置tag值进行区分
        appView.tag = 1000 + index;
        [self.contentView addSubview:appView];
    }
}

- (void)updateWithModel:(SubjectModel*)model
{
    self.subjectTitleView.text = model.title;
    [self.subjectImageView sd_setImageWithURL:[NSURL URLWithString:model.img]];
    [self.subjectDescImageView sd_setImageWithURL:[NSURL URLWithString:model.desc_img]];
    self.textView.text = model.desc;
    self.textView.editable = NO;
    self.textView.backgroundColor = [UIColor clearColor];
    
    //更新SubjectAppView的界面
    [self updateAppView:model.applications];
    //布局SubjectAppView的位置
    [self setNeedsLayout];
}

- (void)updateAppView:(NSArray*)appModelArray{
    for (int index = 0; index < 4; index++) {
        SubjectAppView *appView = (SubjectAppView*)[self.contentView viewWithTag:1000+index];
        if (index < appModelArray.count) {
            //界面不隐藏
            appView.hidden = NO;
            SubjectApplicationModel *model = appModelArray[index];
            //使用application的model更新AppView的界面
            [appView updateWith:model];
        }else{
            //超出appModel数组个数的view隐藏掉
            appView.hidden = YES;
        }
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    //设置各个AppView的位置
    CGFloat xPos  = self.subjectImageView.frame.origin.x + self.subjectImageView.bounds.size.width + 5;
    CGFloat yStartPos = self.subjectImageView.frame.origin.y;
    CGFloat height =  self.subjectImageView.bounds.size.height/4.0;
    CGFloat width = kScreenWidth - self.subjectImageView.bounds.size.width - 40;
    //布局4个view
    for (int index = 0; index < 4; index++) {
        SubjectAppView *appView = [self.contentView viewWithTag:1000+index];
        appView.frame = CGRectMake(xPos, yStartPos+index*height, width, height);
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
